package com.kdtech.analyse.app;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;

/**
 * @author dhy
 * @name 汽车之家
 * @link http://m.autohome.com.cn/
 */
public class AutohomeAppAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://m.autohome.com.cn/[a-z]*/[0-9-]*.html",
		"http://m.autohome.com.cn/[a-z]*/[0-9]*/[0-9-]*.html",
		"http://club.m.autohome.com.cn/bbs/thread-[a-z]*-[0-9]*-[0-9]*-1.html",
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		
		title =doc.select("h1").text();
		if(StringUtils.isBlank(title))
			title =doc.select("h1.post-title").text();
		
		if(doc.select(".shuoke-details p").first()!=null)
			date=DateUtils.matchDate(doc.select(".shuoke-details p").first().text());
		if(doc.select(".news-details p").first()!=null)
			date=DateUtils.matchDate(doc.select(".news-details p").first().text());
		if(date==null && doc.select("header").first() != null)
			date=DateUtils.matchDate(doc.select("header").first().text());
		
		content =HtmlCleaner.getContentHtml(url, doc.select("section.details"));
		if(StringUtils.isBlank(content))
			content =HtmlCleaner.getContentHtml(url, doc.select("div.conttxt"));
		
		author=JSoupUtils.matchAuthor(doc, "作者：");
		Elements authorList = doc.select("div.brief");
		if(authorList.size() > 0)
			author = authorList.get(0).text();
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setAuthor(author);
		news.setContent(content);
		news.setDate(date);

		return news;

	}

	

	

	
}

